package com.chinasoft.back.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @author 中软zhang
 * @create 2023-08-29 11:13
 */
@RestController
public class UploadController {

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String doUpload(HttpServletRequest request, MultipartFile file) throws IOException {

        String realPath = request.getSession().getServletContext().getRealPath("/");
        System.out.println(realPath);
        if (file != null) {
            String originalFilename = file.getOriginalFilename();
            // 产生一个不重复的名字
            String uuidName = UUID.randomUUID().toString();
            // 取文件的后缀
            String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 得到新文件名称
            String name = uuidName + ext;
            String dir = uuidName.substring(0, 3);
            String workDir = realPath + "imgdir/" + dir;
            File dirFile = new File(workDir);
            // 创建 子目录， 用来放文件
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            System.out.println(dir + "/" + name);
            File newFile = new File(workDir + "/" + name);
            file.transferTo(newFile);
        }
        return "success upload";
    }
}
